package cn.schoolwow.util.test.module.replaceFile.parent.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.resource.QueryResource;
import cn.schoolwow.util.domain.replace.ReplaceFile;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class RegexStringReplaceFileProcessFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        copyFile(flowContext);
        replaceFile(flowContext);
    }

    @Override
    public String name() {
        return "正常字符串替换文件测试流程";
    }

    private void copyFile(FlowContext flowContext){
        String filePath = "regex.txt.copy";
        QueryResource.newQuery("正则替换文件", "src/test/resources/module/replaceFile/regex.txt")
                .execute()
                .copyToFile(filePath);
        File file = new File(filePath);
        flowContext.putCurrentFlowData("file", file);
    }

    private void replaceFile(FlowContext flowContext) throws IOException {
        File file = (File) flowContext.checkData("file");

        ReplaceFile.queryFile(file)
                .addRegexReplaceString(
                        ".addColumn\\(\"(.*) \\\\\"(.*)\\\\\"\\\"\\)",
                        ".addColumnAs(\"$1\",\"$2\")"
                )
                .replaceFile();

        String content = QueryResource.newQuery("正则文件", file.getAbsolutePath())
                .execute()
                .getAsString();

        File expectFile = new File("src/test/resources/module/replaceFile/regex.replace.txt");
        String expectContent = FileUtils.readFileToString(expectFile, StandardCharsets.UTF_8);
        Assert.assertEquals(expectContent+"\r\n", content);
    }
}
